﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace MyOpenFileDialog
{
    /// <summary>
    /// OpenFileDialog.xaml 的交互逻辑
    /// </summary>
    public partial class OpenFileDialog : Window
    {
        private OpenFileDialogViewModel _dataContext;

        /// <summary>
        /// 自定义的OpenFileDialog
        /// </summary>
        /// <param name="filter">扩展名过滤条件</param>
        /// <param name="multiSelect">是否可以多选</param>
        public OpenFileDialog(string filter = "全部文件(*.*)|*.*", bool multiSelect = false)
        {
            InitializeComponent();
            _dataContext = new OpenFileDialogViewModel(filter, multiSelect);
            _dataContext.AfterOpenFile += (s, e) => { this.DialogResult = true; };
            DataContext = _dataContext;
        }

        private void ButtonOk_Click(object sender, RoutedEventArgs e)
        {
            if (!string.IsNullOrWhiteSpace(File))
            {
                this.DialogResult = true;
            }
        }

        /// <summary>
        /// 选中的文件
        /// </summary>
        public string File
        {
            get
            {
                if (_dataContext.SelectedFiles != null && _dataContext.SelectedFiles.Count > 0)
                {
                    return _dataContext.SelectedFiles[0].Path;
                }
                return null;
            }
        }

        /// <summary>
        /// 选中的多个文件
        /// </summary>
        public List<string> Files
        {
            get
            {
                List<string> list = new List<string>();

                if (_dataContext.SelectedFiles != null)
                {
                    list = _dataContext.SelectedFiles.Where(p=>p.Type == PathType.File).Select(p => p.Path).ToList();
                }
                return list;
            }
        }

        private void ButtonCancel_Click(object sender, RoutedEventArgs e)
        {
            DialogResult = false;
        }

        private void HandleDoubleClick(object sender, MouseButtonEventArgs e)
        {
            _dataContext.OpenOrDoubleClickCommand.Execute(null);
        }

        private void TreeViewSelectedItemChanged(object sender, RoutedEventArgs e)
        {
            TreeViewItem item = sender as TreeViewItem;
            if (item != null)
            {
                item.BringIntoView();
                e.Handled = true;
            }
        }
    }
}
